package CellEngine;

import java.util.Date;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.io.*;

public class Logger {
	private DateFormat timestampFormat;
	private boolean logFileOutput, consoleOutput, timestamp;
	private File logDirectory, logFile;
	private String logFileName;
	
	public Logger(boolean consoleOutput, boolean logFileOutput, boolean timestamp, String timestampFormat)
	{
		this.consoleOutput = consoleOutput;
		this.logFileOutput = logFileOutput;
		if(logFileOutput)
		{
			logDirectory = new File("log");
			DateFormat logFileNameTimestamp = new SimpleDateFormat("yyyy.MM.dd_HH.mm.ss");
			logFileName = "log" + File.separator/* + "CellEngine_"*/ + logFileNameTimestamp.format(new Date()) + ".txt";
			logFile = new File(logFileName);
		}
		this.timestamp = timestamp;
		if(timestamp)
			this.timestampFormat = new SimpleDateFormat(timestampFormat);
	}
	public void write(String write) { log(write, false); }
	public void writeErr(String write) { log(write, true); }
	public synchronized void log(String write, boolean isError)
	{
		String logEntry = new String();
		if(timestamp)
			logEntry += timestampFormat.format(new Date()).concat(" ");
		logEntry += write;
		if(consoleOutput)
			if(isError)
				System.err.println(logEntry);
			else
				System.out.println(logEntry);
		if(logFileOutput)
		{
			if(!logDirectory.isDirectory() || !logDirectory.exists())
				logDirectory.mkdir();
			if(!logFile.isFile() || !logFile.exists())
			{
				try
				{
					logFile.createNewFile();
				} catch(Exception e) {
					loggerException("Unable to create output file '" + logFile.getAbsolutePath() + "'");
					loggerException(e.getStackTrace().toString());
					return;
				}
			}
			if(!logDirectory.isDirectory() || !logDirectory.exists() || !logFile.isFile() || !logFile.exists())
			{
				loggerException("Could not create the path or output file '" + logFile.getAbsolutePath() + "'");
				return;
			}
			Writer logWriter = null;
			try
			{
				logWriter = new BufferedWriter(new FileWriter(logFile, true));
				logWriter.write(logEntry + StaticDefinitions.textFileNewline);
			} catch(Exception e) {
				loggerException("Unable to write to output file '" + logFile.getAbsolutePath() + "'");
				loggerException(e.getStackTrace().toString());
				return;
			} finally {
				try
				{
					if(logWriter != null)
						logWriter.close();
				} catch(Exception e) {
					loggerException("Unable to close output stream!");
					loggerException(e.getStackTrace().toString());
				}
			}
		}
		// TODO: File output
	}
	
	// Only to be called if an exception within the logger occurs
	private void loggerException(String error)
	{
		System.err.println("[l!] " + error);
	}
}
